package com.tianyu.sports.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.tianyu.sports.bean.SmsInfo;
import com.tianyu.sports.dao.VipinfoHistoryMapper;
import com.tianyu.sports.dao.VipinfoMapper;
import com.tianyu.sports.enums.ResultEnum;
import com.tianyu.sports.exception.VipException;
import com.tianyu.sports.po.Vipinfo;
import com.tianyu.sports.po.VipinfoHistory;
import com.tianyu.sports.service.VipServiceImpl;
import com.tianyu.sports.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Jzen
 * @Title: sports
 * @Package com.tianyu.sports.service.impl
 * @Description: ${todo}
 * @date 2018/5/28 15:39
 */
@Service
public class VipService implements VipServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(VipService.class);

    @Autowired
    private VipinfoMapper vipinfoMapper;

    @Autowired
    private VipinfoHistoryMapper vipinfoHistoryMapper;

    /***
     *
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public SmsInfo getSmsInfo(String phone) {
        logger.info("获取手机号为：phone:{}",phone);
        if(phone != null && !phone.equals("") && PhoneFormatCheckUtils.isPhoneLegal(phone)){
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            SendSmsResponse sms = null;
            SmsInfo smsInfo = new SmsInfo();
            try {
                sms = SmsDemo.sendSms (phone,"天域体育","SMS_135040354","{\"code\":\""+verifyCode+"\"}");
            } catch (ClientException e) {
                e.getStackTrace ();
            }
            if(sms.getCode () != null && ContantUtil.MSGCODE.equals (sms.getCode ())){
                logger.info("获取手机号为：phone:{},发送验证码为:{},发送状态为:{}",phone,verifyCode,sms.getCode ());
                smsInfo.setPhoneNumber (phone);
                smsInfo.setVerifyCode (verifyCode);
            }else{
                logger.info("获取手机号为：phone:{},发送验证码为:{},发送状态为:{}",phone,verifyCode,sms.getCode ());
                throw new VipException(ResultEnum.SMS_CODE_ERROR);
            }
            return smsInfo;
        }else {
            throw new VipException(ResultEnum.ERROR_PHONE);
        }
    }

    /**
     * 注册会员信息
     *
     * @return
     */
    public Map putMembers(VipinfoHistory vipinfoHistory) {
        logger.info("会员：{},进行注册",vipinfoHistory.getUsername());
        int vipNum = vipinfoMapper.getVipNum();
        Map<String,String> map = new HashMap(2);
        int statu = vipinfoHistoryMapper.insertVipinfoHistory(vipinfoHistory);
        if(statu == 0){
            throw new VipException(ResultEnum.REGISTER_ERROR);
        }else {
            map.put("price",VipUtil.getNowUserPrice(vipNum));
            map.put("vipid",String.valueOf(vipinfoHistory.getId()));
        }
        return map;
    }

//    public String putMembers(Vipinfo vipinfo) {
//        logger.info("会员：{},进行注册",vipinfo.getUsername());
//        int vipNum = vipinfoMapper.getVipNum();
//        int vipOrder = VipUtil.getVipOrder(++vipNum);
//        String vipNumberOrder = VipUtil.getVipNumberOrder(vipOrder);
//        Map<String,String> map = new HashMap(2);
//        vipinfo.setVipnumber(vipNumberOrder);
//        vipinfo.setStatu(0);
//        int statu = vipinfoMapper.insertSelective(vipinfo);
//        int i = vipinfoMapper.updateVipnumByOrder(vipOrder);
//        if(statu == 1 && i == 1){
//            SendSmsResponse sms = null;
//            try {
//                sms = SmsDemo.sendSms (vipinfo.getPhone(),"天域体育","SMS_136870028","{\"vipnumber\":\""+vipNumberOrder+"\"}");
//            } catch (ClientException e) {
//                e.getStackTrace ();
//            }
//            return vipNumberOrder;
//        }else{
//            throw new VipException(ResultEnum.INSERT_ERROR);
//        }
//
//    }

    /**
     * 检查电话号
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhone(String phone) {
        logger.info("检查手机号为：{}",phone);
        int i = vipinfoMapper.selectByPhone(phone);
        if(i > 0){
            throw new VipException(ResultEnum.INFO_REPEAT);
        }
    }

    /**
     * 检查身份证号
     *
     * @param idNumber
     * @return
     */
    @Override
    public void checkIDNumber(String idNumber) {
        logger.info("检查身份证号为：{}",idNumber);
        int i = vipinfoMapper.checkIDNumber(idNumber);
        if(i > 0){
            throw new VipException(ResultEnum.INFO_REPEAT);
        }
    }

    /**
     * 注册账号信息反馈
     *
     * @param id
     * @param stuta
     */
    @Override
    public Map<String, String> registerSuccess(Integer id,String ordernumber) {
        logger.info("注册账号信息反馈id:{},ordernumber:{}",id,ordernumber);
        String vipNumberOrder = null;
        Map<String, String> result = new HashMap<>(2);
        int vipNum = vipinfoMapper.getVipNum();
        logger.info("注册账号总数{}"+vipNum);
        Vipinfo vipinfo = vipinfoMapper.selectVipInfoHistory(id);

        Map<String, String> map = WxRequestUtils.queryOrderByH5Pay(ordernumber);
        String trade_state = map.get("trade_state");

        result.put("stuta","-1");
        result.put("code",trade_state);
        result.put("vipnumber",vipNumberOrder);

        if("SUCCESS".equals(trade_state)){
            if(vipinfo != null ){
                int num = VipUtil.getVipOrder(vipNum+1);
                vipNumberOrder = VipUtil.getVipNumberOrder(num);
                vipinfo.setCreattime(new Date());
                vipinfo.setEndtime(VipUtil.getNextTime(new Date()));
                vipinfo.setStatu(0);
                vipinfo.setVipnumber(vipNumberOrder);
                try{
                    int i = vipinfoMapper.insertSelective(vipinfo);
                    if(i == 0){
                        logger.info("注册失败用户信息为{},当前会员总数为{}",vipinfo.getUsername(),vipNum);
                        throw new VipException(ResultEnum.INSERT_ERROR);
                    }else {
                        vipinfoMapper.updateVipnumByOrder(num);
                        logger.info("注册成功用户信息为{},当前会员总数为{}",vipinfo.getUsername(),num);
                        result.put("stuta","0");
                        result.put("Msg","注册成功");
                        result.put("vipnumber",vipNumberOrder);
                        SendSmsResponse sms = null;
                        try {
                            sms = SmsDemo.sendSms (vipinfo.getPhone(),"天域体育","SMS_136870028","{\"vipnumber\":\""+vipNumberOrder+"\"}");
                        } catch (ClientException e) {
                            e.getStackTrace ();
                        }
                        return result;
                    }
                }catch (Exception e){
                    throw new VipException(ResultEnum.UNKNOW_ERROR);
                }
            }else {
                logger.info("注册失败无法获取注册信息");
                result.put("Msg","注册失败无法获取注册信息");
            }
        }else {
            logger.info(trade_state);
            result.put("Msg",map.get("trade_state_desc"));
        }
        return result;
    }

    @Override
    public Map<String, String> registerSuccessByGZH(Integer id ) {
        logger.info("注册账号信息反馈id:{}}",id);
        String vipNumberOrder = null;
        Map<String, String> result = new HashMap<>(2);
        int vipNum = vipinfoMapper.getVipNum();
        logger.info("注册账号总数{}"+vipNum);
        Vipinfo vipinfo = vipinfoMapper.selectVipInfoHistory(id);
        result.put("stuta","-1");
        result.put("Msg", "注册失败");
        result.put("vipnumber",vipNumberOrder);
        if(vipinfo != null ) {
            int num = VipUtil.getVipOrder(vipNum + 1);
            vipNumberOrder = VipUtil.getVipNumberOrder(num);
            vipinfo.setCreattime(new Date());
            vipinfo.setEndtime(VipUtil.getNextTime(new Date()));
            vipinfo.setStatu(0);
            vipinfo.setVipnumber(vipNumberOrder);
            try {
                int i = vipinfoMapper.insertSelective(vipinfo);
                if (i == 0) {
                    logger.info("注册失败用户信息为{},当前会员总数为{}", vipinfo.getUsername(), vipNum);
                    throw new VipException(ResultEnum.INSERT_ERROR);
                } else {
                    vipinfoMapper.updateVipnumByOrder(num);
                    logger.info("注册成功用户信息为{},当前会员总数为{}", vipinfo.getUsername(), num);
                    result.put("stuta", "0");
                    result.put("Msg", "注册成功");
                    result.put("vipnumber", vipNumberOrder);
                    SendSmsResponse sms = null;
                    try {
                        sms = SmsDemo.sendSms(vipinfo.getPhone(), "天域体育", "SMS_136870028", "{\"vipnumber\":\"" + vipNumberOrder + "\"}");
                    } catch (ClientException e) {
                        e.getStackTrace();
                    }
                    return result;
                }
            } catch (Exception e) {
                throw new VipException(ResultEnum.UNKNOW_ERROR);
            }
        }else{
            throw new VipException(ResultEnum.REGISTER_ERROR);
        }
    }
    /**
     * 微信支付
     *
     * @return
     * @param totalfee
     * @param userip
     */
    public Map<String, String> weixinPay(String totalfee,String userip) {
        logger.info("微信支付为:{},调用IP为:{}",totalfee,userip);
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
        long order = snowflakeIdWorker.nextId();
        logger.info("生产订单号为{}",order);
        Map<String, String> stringStringMap = WxRequestUtils.weixinH5Pay(totalfee,userip,String.valueOf(order));
        logger.info("支付回调信息为：{}",stringStringMap);
        return stringStringMap;
    }
    /**
     * 微信公众号支付
     * @param totalfee
     * @param userip
     * @param openid
     * @return
     */
    public Map<String,String> weixinPublicPay(String totalfee,String userip,String openid){
        logger.info("微信支付为:{},调用IP为:{}",totalfee,userip);
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
        long trade = snowflakeIdWorker.nextId();
        logger.info("生产订单号为{}",trade);
        Map<String,String> stringStringMap =  WxRequestUtils.weixinPublicPay(totalfee,String.valueOf(trade),userip,openid);
        logger.info("支付回调信息为：{}",stringStringMap);
        return stringStringMap;
    }
}
